package com.lee.auth.sms;

import com.lee.common.exception.CustomException;
import com.lee.common.exception.FailureStatus;
import com.lee.common.vo.ResultVO;
import lombok.AllArgsConstructor;
import org.apache.commons.lang3.RandomStringUtils;
import org.springframework.web.bind.annotation.*;

import java.util.regex.Pattern;

/**
 * @author lee HN
 * @date 2021/4/13 16:37
 */
@RestController
@RequestMapping("/sms")
@AllArgsConstructor
public class SmsController {

    private final SmsService smsService;

    private static final Pattern pattern = Pattern.compile("^1[3-9]\\d{9}$");

    public static final CustomException NUMBER_WRONG = new CustomException(FailureStatus.BAD_PARAM, "phone number is wrong");

    public static final int CODE_LEN = 4;

    public void sendSmsCode(String account, String scene) {
        if (!pattern.matcher(account).matches()) throw NUMBER_WRONG;
        String code = RandomStringUtils.randomNumeric(CODE_LEN);
        smsService.sendSmsCode(account, scene, code);
    }

    @PostMapping("/sendCode/{scene}")
    public ResultVO<Void> sendSms(@RequestParam String phone, @PathVariable String scene) {
        sendSmsCode(phone, scene);
        return ResultVO.success();
    }

    /*@GetMapping("/sendCodeToMe/{scene}")
    public ResponseVO<Void> sendSmsToMe(@PathVariable String scene) {
        sendSmsCode(AuthContextVerifier.isAuthenticated().username, scene);
        return ResponseVO.success();
    }*/

}
